﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using TCKQKL.Service.LookupClient;
using TCKQKL.FrontEnd.DataModel;

namespace StockTrader.FrontEnd.OnlineOrderMonitor
{
    public partial class frmMain : Form
    {
        private System.Timers.Timer tm = new System.Timers.Timer();

        public frmMain()
        {
            InitializeComponent();

        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            try
            {
                GetOrderList();

                tm.Interval = 5000;
                tm.Enabled = true;
                tm.Elapsed += new System.Timers.ElapsedEventHandler(tm_Elapsed);
            }
            catch (System.Exception ex)
            {
                DialogResult result = MessageBox.Show("Không kết nối được tới máy chủ dịch vụ. Hãy khởi động lại ứng dụng.\n" + ex.Message, "Sự cố", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Environment.Exit(1);
            }
        }

        void tm_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                GetOrderList();
            }
            catch
            {
                return;
            }
        }

        private void frmMain_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue.Equals(13))
                LoadNextOrder("COMPLETED");
        }

        private void LoadNextOrder(string orderType)
        {
            try
            {
                LSClient client = new LSClient();

                if (!string.IsNullOrEmpty(lblLineNum.Text))
                    client.UpdateOrderStatus(Convert.ToInt32(lblLineNum.Text), orderType);


                OrdersOnlineUI order = client.getNewestOrder("", "PROCESSING");

                if (order != null)
                {
                    if (!order.OrderType.Equals("PLACE"))
                    {
                        OrdersOnlineUI oOrder = client.getOrderOriginal(order.OrderId);
                        lbloAccountNo.Text = oOrder.AccountNo;
                        lbloOrderSide.Text = oOrder.OrderSide;
                        lbloSymbol.Text = oOrder.Symbol;
                        lbloQuantity.Text = oOrder.Quantity.ToString("N0");
                        lbloPrice.Text = oOrder.Price;
                    }
                    lblAccountNo.Text = order.AccountNo;
                    lblOrderSide.Text = order.OrderSide;
                    lblSymbol.Text = order.Symbol;
                    lblQuantity.Text = order.Quantity.ToString("N0");
                    lblPrice.Text = order.Price;
                    lblLineNum.Text = order.OrderId.ToString();

                    switch (order.OrderType)
                    {
                        case "PLACE":
                            if (order.OrderSide.Equals("BUY"))
                                topSpliter.Panel1.BackColor = Color.MediumTurquoise;
                            else
                                topSpliter.Panel1.BackColor = Color.Khaki;
                            break;
                        case "CHANGE":
                            if (order.OrderSide.Equals("BUY"))
                                topSpliter.Panel1.BackColor = Color.PaleGreen;
                            else
                                topSpliter.Panel1.BackColor = Color.PaleGreen;
                            break;
                        case "CANCEL":
                            topSpliter.Panel1.BackColor = Color.Pink;
                            break;
                    }
                    client.Close();
                }
                else
                {
                    ClearOrderWait();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Không kết nối được tới máy chủ dịch vụ. Hãy khởi động lại ứng dụng.\n"
                + ex.Message, "Sự cố", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Environment.Exit(1);
            }
        }

        private void GetOrderList()
        {
            LSClient client = new LSClient();
            List<OrdersOnlineUI> nList = client.getOrderListByStatus("");
            List<OrdersOnlineUI> cList = client.getOrderListByStatus("COMPLETED");
            List<OrdersOnlineUI> sList = client.getOrderListByStatus("SKIP");
            client.Close();
            MethodInvoker UpdateUI = delegate
            {
                grvNew.DataSource = nList;
                GridLayerOut(grvNew);

                grvCompleted.DataSource = cList;
                GridLayerOut(grvCompleted);

                grvSkip.DataSource = sList;
                GridLayerOut(grvSkip);
            };
            if (grvNew.InvokeRequired || grvCompleted.InvokeRequired || grvSkip.InvokeRequired)
            {
                grvNew.Invoke(UpdateUI);
                grvCompleted.Invoke(UpdateUI);
                grvSkip.Invoke(UpdateUI);
            }
            else
                UpdateUI();
        }

        private void GridLayerOut(DataGridView grv)
        {
            grv.Columns["OrderId"].HeaderText = "Số";
            grv.Columns["OrderType"].HeaderText = "Loại";
            grv.Columns["AccountNo"].HeaderText = "Số TK";
            grv.Columns["OrderSide"].HeaderText = "Bên";
            grv.Columns["Symbol"].HeaderText = "MCK";
            grv.Columns["Price"].HeaderText = "Giá";
            grv.Columns["Quantity"].HeaderText = "KL";
            grv.Columns["TimeStamp"].HeaderText = "Giờ";

            grv.Columns["OrderMode"].Visible = false;
            grv.Columns["OrderClass"].Visible = false;
            grv.Columns["ExpireDate"].Visible = false;
            grv.Columns["OrderNo"].Visible = false;
            grv.Columns["OrderSpec"].Visible = false;
            grv.Columns["OpenDate"].Visible = false;

            grv.Columns["Quantity"].DefaultCellStyle.Format = "N0";
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            LoadNextOrder("COMPLETED");
            GetOrderList();
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            LSClient client = new LSClient();

            if (!string.IsNullOrEmpty(lblLineNum.Text))
                client.UpdateOrderStatus(Convert.ToInt32(lblLineNum.Text), "");

            Environment.Exit(1);
        }

        private void ClearOrderWait()
        {
            lblAccountNo.Text = String.Empty;
            lblOrderSide.Text = String.Empty;
            lblSymbol.Text = String.Empty;
            lblQuantity.Text = String.Empty;
            lblPrice.Text = String.Empty;
            lblLineNum.Text = String.Empty;
        }

        private void btnSkip_Click(object sender, EventArgs e)
        {
            LoadNextOrder("SKIP");
            GetOrderList();
        }

        private void frmMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            LSClient client = new LSClient();

            if (!string.IsNullOrEmpty(lblLineNum.Text))
                client.UpdateOrderStatus(Convert.ToInt32(lblLineNum.Text), "");
        }

        private void lblOrderSide_Click(object sender, EventArgs e)
        {

        }

        private void label3_Click(object sender, EventArgs e)
        {

        }

        private void label2_Click(object sender, EventArgs e)
        {

        }
    }
}
